package com.xialuo.logic.controller;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.xialuo.common.lang.Result;
import com.xialuo.logic.entity.Emp;
import com.xialuo.exception.MyException;
import com.xialuo.logic.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


@Controller
public class IndexController {


    @GetMapping("/notRole")
    public String notRole() {
       System.out.println("没有权限访问！！！！！！！！！");
        return "error/notrole";

    }
    @GetMapping("/notLogin")
    public String notLogin() {

        return "admin/login";

    }
    @GetMapping("/toLogin")
    public String toLogin(String userName,String passWord) {

        //1、获取Subject
      //  Subject subject = SecurityUtils.getSubject();

        //2、封装用户数据
       // UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);

        //3、执行登录方法

        try {

           //subject.login(token); //登陆成功

            return "redirect:/index";

        } catch (AuthenticationException e) {

            //登录失败 返回页面错误信息 或者不直接返回
            e.printStackTrace();
            return "redirect:/notLogin";
        }



    }
    @GetMapping("/index")
    @RequiresAuthentication
    @ResponseBody
    public Result index(Model model) {

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Result result = Result.success(200, "操作成功", user);
        model.addAttribute("name","baoyanpei");
        return result;

    }
    @GetMapping("/list")
    public String listEmp(Model model,  @RequestParam("id") String id) throws JSONException, MyException {


        throw new MyException("服务器内部错误");

    }
    @GetMapping("/loginOut")
    public String loginOut() {

        System.out.println("用户登出-----------");
        Subject subject =SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/notLogin";

    }

}
